layui.use(['form', 'laydate'], function () {

    var form = layui.form;
    var laydate = layui.laydate;

    //执行一个laydate实例
    laydate.render({
        elem: '#date'
    });

    var orderId = GetQueryStringEncode("orderId");
    var oper = GetQueryStringEncode("oper"); // edit 编辑 detail 详情 add 新增

    initFinanicalInfo();

    // 监听金融产品下拉框
    form.on('select(financialProductsName)', function (data) {
        var id = $("#financialProductsName option:selected")[0].getAttribute("value1")
        initFinanicalInfo(id);
    });

    // 初始化金融产品
    function initFinanicalInfo(id) {
        var paramData = {};
        if (id) {
            paramData = {"type": 1, "finanicalId": id};
        } else {
            paramData = {"type": 1};
        }
        $.axse(hostUrl + "/finanical/info",
            paramData,
            function (res) {
                if (res.status == 1) {
                    var data = res.data;
                    if (!id) {
                        var html = "<option value='' selected=''>请选择</option>";
                        $.each(data, function (index, value) {
                            html += "<option value1='" + value.id + "' value='" + value.finanicalName + "'>" + value.finanicalName + "</option>";
                        });
                        $("#financialProductsName").html(html);
                        form.render();
                    } else {
                        if (data != null && data.length > 0) {
                            $("#remaidRatio").val(data[0].remaidRatio);
                        }
                    }
                } else {
                    Layer.showFailMsg(res.msg, 0);
                }
            },
            function () {
                Layer.showFailMsg("系统网络开小差了，请稍后重试");
            })
    }

    if ($.common.isNotEmpty(orderId)) {
        // 初始化数据
        initData();
        // 编辑隐藏关联客户按钮
        if (oper == "edit") {
            $(".associated-customers").addClass("layui-hide");
            // 显示客户信息
            $("#hiddenInput").removeClass("layui-hide");
        }
    }

    var store_days = 0;
    var car_days = 0;
    var stock_status = 0;

    function initData() {
        $.axse(hostUrl + "/order/orderDetail",
            {"orderId": orderId},
            function (res) {
                if (res.status == 0) {
                    var data = res.data;
                    for (var key in data) {
                        var objData = data[key];
                        // 车型数据 单独处理
                        if (key == "car") {
                            for (var key2 in objData) {
                                // 赋值其他数据
                                $("#" + key2).text(objData[key2]);
                                // 判断车型 是否展示 图片
                                if (key2 == "fuel_type") {
                                    if (objData[key2] == 0 || objData[key2] == 1) {
                                        $("#imgDiv").removeClass("layui-hide");
                                        // 展示图片 遍历图片
                                    }
                                }
                                var domName = key + ".carId";
                                // 车ID赋值
                                if (key2 == "id") {
                                    $("input[name='" + domName + "']").not('.layui-form-radio,input[type=radio]').val(objData[key2]);
                                }
                                if (key2 == "store_date") {
                                	$("#" + key2).text(new Date(objData[key2]).Format("yyyy-MM-dd hh:mm:ss")); 
                                }
                                // 车的预警状态
                                if (key2 == "store_days") {
                                    store_days = objData[key2];
                                }
                                if (key2 == "car_days") {
                                    car_days = objData[key2];
                                }
                                if (key2 == "stock_status") {
                                    stock_status = objData[key2];
                                }
                            }
                        } else if (key == "retrofitting" || key == "retailmanagerGive" || key == "otherServices") {
                            // 加装 赠送 其他服务单独处理
                            // productName retailPrice costPrice
                            // 加装项目
                            if (key == "retrofitting") {
                                //$("#addProject2").empty();
                                $("#addProject").html(createHtml("retrofitting", "加装项目名称", objData));
                            }
                            // 赠送
                            if (key == "retailmanagerGive") {
                                //$("#giftProject2").empty();
                                $("#giftProject").html(createHtml("retailmanagerGive", "赠送项目名称", objData));
                            }
                            // 其他
                            if (key == "otherServices") {
                                //$("#otherProject2").empty();
                                $("#otherProject").html(createHtml("otherServices", "其它服务名称", objData));
                            }
                            // 控制小按钮
                            if (oper == "detail") {
                                $(".divAddDom").addClass("layui-hide")
                                $(".divDeleteDom").addClass("layui-hide")
                            }
                        } else if (key == "ima") {
                            if($.common.isNotEmpty(objData)) {
                                // 图片处理 数组
                                for (var i = 0; i < objData.length; i++) {
                                    // 0-身份证正面 1-身份证反面  2-行驶证 3-车辆登记证 4-完税证明 5-交强险保单
                                    if ($.common.isNotEmpty(objData[i].imaUrl)) {
                                        if (objData[i].imaType == 0) {
                                            $("#sfz1Img").html(createImg(objData[i].imaUrl));
                                        } else if (objData[i].imaType == 1) {
                                            $("#sfz2Img").html(createImg(objData[i].imaUrl));
                                        } else if (objData[i].imaType == 2) {
                                            $("#xszImg").html(createImg(objData[i].imaUrl));
                                        } else if (objData[i].imaType == 3) {
                                            $("#cldjzImg").html(createImg(objData[i].imaUrl));
                                        } else if (objData[i].imaType == 4) {
                                            $("#wszmImg").html(createImg(objData[i].imaUrl));
                                        } else if (objData[i].imaType == 5) {
                                            $("#jqxbdImg").html(createImg(objData[i].imaUrl));
                                        }
                                    }
                                }
                            }
                        } else if (key == "remark") {
                            $("#remark").text(objData);
                        } else {
                            // 存储多选框值
                            var dataObj;
                            for (var key2 in objData) {
                                var domName = key + "." + key2
                                // input 赋值 排除掉 radio
                                if(oper == "detail") {
                                    $("input[name='" + domName + "']").val(objData[key2]);
                                } else {
                                    $("input[name='" + domName + "']").not('.layui-form-radio,input[type=radio]').val(objData[key2]);
                                }
                                // select 赋值
                                $("select[name='" + domName + "']").val(objData[key2]);

                                // 判断购车方式
                                if (key == "retailOrder" && key2 == "buyCarType") {
                                    // 订单主表
                                    if (objData[key2] == 1) {
                                        // 全款 隐藏分期内容
                                        $(".fullPayment").addClass("layui-hide");
                                        $("#financialPrice").removeAttr("lay-verify");
                                        $("#term").removeAttr("lay-verify");
                                        $("#downPaymentRatio").removeAttr("lay-verify");
                                        $("#financialProductsName").removeAttr("lay-verify");
                                        $("#financialPrice").removeAttr("lay-verify");
                                    }
                                    if(oper == "detail") {
                                        // 单选按钮赋值 购车方式
                                        if(objData[key2] == 0) {
                                            $("input[name='" + domName + "']").val("分期")
                                        } else if(objData[key2] == 1){
                                            $("input[name='" + domName + "']").val("全款")
                                        }
                                    } else {
                                        // 单选按钮赋值 购车方式
                                        $("input[name='" + domName + "'][value='" + objData[key2] + "']").attr("checked", true);
                                    }

                                }
                                // 交车确认 按钮赋值
                                if (key == "orderStatus" && key2 == "retailOrderStatu") {
                                    if (objData[key2] >= 1) {
                                        objData[key2] = 1;
                                    }
                                    if(oper == "detail") {
                                        // 单选按钮赋值 购车方式
                                        if (objData[key2] == 0) {
                                            $("input[name='" + domName + "']").val("已订未交")
                                        } else if(objData[key2] == 1){
                                            $("input[name='" + domName + "']").val("已交车")
                                        }
                                    } else {
                                        // 单选按钮赋值 购车方式
                                        $("input[name='" + domName + "'][value='" + objData[key2] + "']").attr("checked", true);
                                    }
                                }
                                // 证件类型处理
                                if(key == "customer" && key2 == "type" && oper == "detail") {
                                	var customerType = "";
                                	if(objData[key2] == 0) {
                                		customerType = '身份证';
                                	} else if(objData[key2] == 1){
                                		customerType = '驾照';
                                	}else {
                                		customerType = '护照';
                                	}
                                	$("input[name='" + domName + "']").val(customerType)
                                }
                                // 多选框赋值
                                if(key == "insurance" && key2 == "insuranceTypeName") {
                                    dataObj = objData[key2];
                                }
                            }
                        }
                    }
                    form.render();
                    // 预警状态 修改为图标
                    iconByValue(stock_status, store_days, car_days);
                    // 多选框赋值
                    mulSelectValueRender(dataObj);
                } else {
                    Layer.showFailMsg(res.msg, 0);
                }
            },
            function () {
                Layer.showFailMsg("系统网络开小差了，请稍后重试");
            })
    }
    
  

    // 多选框赋值
    function mulSelectValueRender(dataObj) {
        var insuranceArr = [];
        if($.common.isNotEmpty(dataObj)) {
            var data = dataObj.split(",");
            for (var k = 0; k < data.length; k++) {
                insuranceArr.push(data[k]);
            }
            $("select[name='insurance.insuranceTypeName']").val(insuranceArr);
            form.render();
        }
    }

    // 图片点击事件
    $("#imgDiv img").on("click",function () {
        var src = this.getAttribute("src");
        layer.photos({
            photos: {
                title: "查看头像",
                data: [{
                    src: src
                }]
            },
            shade: .01,
            closeBtn: 1,
            anim: 5
        })
        // onclick='photoPreview(this)'
    })

    function createImg(src) {
        var html = "";
        html += "<img onclick='photoPreview(this)' src='" + src + "'/>";
        return html;
    }

    function createHtml(key, productName, objData) {
        var html = "";
        if($.common.isNotEmpty(objData)) {
            // 清空掉新增时默认的第一行DOM元素
            for (var i = 0; i < objData.length; i++) {
                if (key == "retrofitting") {
                    addProject++;
                }
                if (key == "retailmanagerGive") {
                    giftProject++;
                }
                if (key == "otherServices") {
                    otherProject++;
                }
                if (i == 0) {
                    // 赋值操作 而不是新增dom元素
                    $("input[name='" + key + "[0].productName']").val(objData[i].productName);
                    $("input[name='" + key + "[0].retailPrice']").val(objData[i].retailPrice);
                    $("input[name='" + key + "[0].costPrice']").val(objData[i].costPrice);
                } else {
                    html += createDom(productName, objData[i].productName, objData[i].retailPrice, objData[i].costPrice, i);
                }
                /*html += createDom("零售价格",objData[i].retailPrice);
                html += createDom("成本价格",objData[i].costPrice);*/
            }
        }
        return html;
    }

    function createDom(text, productName, retailPrice, costPrice, i) {
        var html = "";
        /*html += '<div class="layui-form-item layui-col-md4 layui-clear-none">';
            html += '<label class="layui-form-label">'+text+'</label>';
            html += '<div class="layui-input-inline">';
                html += '<input type="text" value="'+value+'" class="layui-input">';
            html += '</div>';
        html += '</div>';*/
        html += "<div class='layui-form-item'>";
        html += '<div class="layui-form-item layui-col-md4 layui-clear-none">';
        html += '<label class="layui-form-label">' + text + '</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="text" name="retailmanagerGive[' + i + '].productName" value="' + productName + '" placeholder="请输入" class="layui-input">';
        html += '</div>';
        html += '</div>';

        html += '<div class="layui-form-item layui-col-md4 layui-clear-none">';
        html += '<label class="layui-form-label">零售价格</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="text" name="retailmanagerGive[' + i + '].retailPrice" value="' + retailPrice + '" placeholder="请输入" class="layui-input">';
        html += '</div>';
        html += '</div>';

        html += '<div class="layui-form-item layui-col-md4 layui-clear-none">';
        html += '<label class="layui-form-label">成本价格</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="text" name="retailmanagerGive[' + i + '].costPrice" value="' + costPrice + '" placeholder="请输入" class="layui-input">';
        html += '<div class="divDeleteDom" value="giftProject" style="position:absolute;left:210px;top:5px;border-radius:20px;">';
        html += '<i class="layui-icon layui-icon-close-fill" style="font-size: 22px;color: #ea420d;"></i>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        return html;
    }

    // 取消按钮
    $("#cancel").on("click", function () {
        closeWindow();
    });

    // 关闭当前弹出窗口
    function closeWindow() {
        //先得到当前iframe层的索引
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index); //再执行关闭
    };

    // 預警圖標
    //根据获取预的警状态的值 从而显示不同状态下的图片
    function iconByValue(status, store_days, car_days) {
         var url = "";
         var status_kl=0;
	 	 if(store_days<45){
	 		status_kl=0;
	 	 }else if(store_days>=45 && store_days<60){
	 		status_kl=1;
	 	 }else if(store_days>=60){
	 		status_kl=2;
	 	 }
	 	 var status_cl=0;
     	 if(car_days<180){
     		status_cl=0;
     	 }else if(car_days>=180 && car_days<360){
     		status_cl=1;
     	 }else if(car_days>60){
     		status_cl=2;
     	 }
     	 
     	 var status=0;
     	 if(status_kl>status_cl){
     		status=status_kl;
     	 }else{
     		status=status_cl;
     	 }
     	 
     	 if(status==0){
     		url="<img src='" + hostUrl + "/static/layuiadmin/images/ico/early_warning_green.png'/>";
     	 }else if(status==1){
     		url="<img src='" + hostUrl + "/static/layuiadmin/images/ico/early_warning_yellow.png'>";
     	 }else if(status==2){
     		url="<img src='" + hostUrl + "/static/layuiadmin/images/ico/early_warning_red.png'/>";
     	 }
         $("#stock_status_days").html(url);
    }
});
// 图片点击预览
function photoPreview(obj) {
    var src = obj.getAttribute("src");
    layer.photos({
        photos: {
            title: "查看头像",
            data: [{
                src: src
            }]
        },
        shade: .01,
        closeBtn: 1,
        anim: 5
    })
}